package com.tolerate.managespringboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tolerate.managespringboot.common.Result;
import com.tolerate.managespringboot.entity.Menu;
import com.tolerate.managespringboot.service.MenuService;
import com.tolerate.managespringboot.mapper.MenuMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Tolerate
 * @description 针对表【sys_menu】的数据库操作Service实现
 * @createDate 2024-08-18 17:22:48
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
        implements MenuService {

    @Override
    public Result getMenuTree() {
        // 获取所有菜单
        List<Menu> menuList = this.list();
        // 获取到根节点的数据
        List<Menu> list = menuList.stream().filter(item -> item.getPid().equals(0)).map((menu) -> {
            menu.setChildren(getChildrenData(menu, menuList));
            return menu;
        }).collect(Collectors.toList());
        return Result.success(list);
    }

    //获取孩子（下级目录）的方法，递归实现
    private List<Menu> getChildrenData(Menu root, List<Menu> allList) {
        List<Menu> children = allList.stream().filter(item -> item.getPid().equals(root.getId())).map(subjectVO -> {
            subjectVO.setChildren(getChildrenData(subjectVO, allList));
            return subjectVO;
        }).collect(Collectors.toList());
        return children;
    }
}




